package com.example.recordingpen_datacollection.config.Interceptor;

import com.alibaba.fastjson.JSONObject;
import com.example.recordingpen_datacollection.config.RateLimitConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;  
import org.springframework.web.servlet.HandlerInterceptor;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.time.Duration;
import java.time.Instant;  
import java.util.Deque;  
import java.util.HashMap;  
import java.util.LinkedList;  
import java.util.Map;  
  
@Component  
public class RateLimitInterceptor implements HandlerInterceptor {
//    private static final int MAX_REQUESTS = 10; // 最大存储的请求数量
    private static final long MINUTE_IN_MILLIS = 60 * 1000; // 1分钟毫秒数

    private final Map<String, Deque<Instant>> requestTimestamps = new HashMap<>();  
  
    @Autowired  
    private RateLimitConfig rateLimitConfig;
  
    @Override  
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {  
        String path = request.getRequestURI(); // 获取请求的URI  
  
        Integer maxRequests = rateLimitConfig.getMaxRequests(path); // 根据路径获取最大请求数  
        if (maxRequests == null) {  
            // 如果没有配置速率限制，允许请求继续  
            return true;  
        }  
  
        Deque<Instant> timestamps = requestTimestamps.computeIfAbsent(path, k -> new LinkedList<>()); // 获取或创建时间戳队列  
  
        Instant now = Instant.now();  
  
        // 添加请求时间戳到队列中  
        synchronized (timestamps) {

            if(timestamps.size()<maxRequests){
                timestamps.addLast(now);
                return true;
            }

  
            // 检查时间差
            System.out.println("ss :"+Duration.between(timestamps.getFirst(), now).toMillis() );
            if (!timestamps.isEmpty() &&  
                Duration.between(timestamps.getFirst(), now).toMillis() < MINUTE_IN_MILLIS) { // 假设所有路径都是1分钟限制，你可以根据maxRequests调整
                // 时间差小于限制时间，拒绝访问  
//                response.setStatus(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE);
//                response.getWriter().write("Too many requests within the limit, access denied.");
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/json; charset=utf-8");
                JSONObject res = new JSONObject();
                res.put("success", "false");
                res.put("code", "413");
                res.put("message", "有效载荷太大");
                PrintWriter out = response.getWriter();
                out.write(res.toString());
                out.flush();
                out.close();
                return false; // 返回false表示请求被拦截  
            }  
        }

        if (timestamps.size() == maxRequests) {
            timestamps.removeFirst(); // 移除最旧的请求时间戳
        }
        timestamps.addLast(now); // 添加新的请求时间戳
        // 允许请求继续处理  
        return true;  
    }  
}